package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.bo.EmployeeRoleAssignBO;
import com.yt.sys.models.dto.EmployeeRoleDTO;
import com.yt.sys.models.dto.RoleDTO;
import com.yt.sys.models.vo.RoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.IEmployeeRoleService;
import com.yt.sys.models.service.IRoleService;
import com.yt.sys.models.bo.EmployeeRoleBO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关联控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:48:29
 */

@RestController
@RequestMapping("/api/userRole")
@Slf4j
@Api(value = "UserRoleApiController",tags = "用户角色关联Api接口")
public class EmployeeRoleApiController {

    @DubboReference
    private IEmployeeRoleService userRoleService;
    
    @DubboReference
    private IRoleService roleService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<EmployeeRoleDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        EmployeeRoleDTO dto = userRoleService.selectById(id);

        return new Result<>(dto);
    }

    @PostMapping("/assignRoles")
    @ApiOperation(value = "为员工分配角色", notes = "为指定员工分配一个或多个角色")
    public Result assignRoles(@RequestBody EmployeeRoleAssignBO assignBO) {
        // 参数校验
        if (assignBO.getEmployeeId() == null || assignBO.getRoleIds() == null || assignBO.getRoleIds().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 先删除该员工已有的所有角色
        Wrapper<EmployeeRoleDTO> deleteWrapper = new EntityWrapper<>();
        deleteWrapper.eq("employee_id", assignBO.getEmployeeId());
        userRoleService.delete(deleteWrapper);

        // 批量插入新的角色分配
        List<EmployeeRoleDTO> employeeRoleList = new ArrayList<>();
        for (String roleId : assignBO.getRoleIds()) {
            EmployeeRoleDTO employeeRole = new EmployeeRoleDTO();
            employeeRole.setEmployeeId(assignBO.getEmployeeId());
            employeeRole.setRoleId(roleId);
            employeeRoleList.add(employeeRole);
        }

        if (!employeeRoleList.isEmpty()) {
            userRoleService.insertBatch(employeeRoleList);
        }

        return new Result();
    }
    
    @GetMapping("/{employeeId}/roles")
    @ApiOperation(value = "获取指定员工已分配的角色列表", notes = "获取指定员工已分配的角色列表")
    public Result<List<RoleVO>> getEmployeeRoles(@PathVariable("employeeId") String employeeId) {
        // 查询员工关联的角色ID列表
        Wrapper<EmployeeRoleDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("employee_id", employeeId);
        List<EmployeeRoleDTO> employeeRoleList = userRoleService.selectList(wrapper);
        
        // 提取角色ID列表
        List<String> roleIds = employeeRoleList.stream()
                .map(EmployeeRoleDTO::getRoleId)
                .collect(Collectors.toList());
        
        // 如果没有角色，返回空列表
        if (roleIds.isEmpty()) {
            return new Result<>();
        }
        
        // 根据角色ID列表查询角色详情
        Wrapper<RoleDTO> roleWrapper = new EntityWrapper<>();
        roleWrapper.in("id", roleIds);
        List<RoleDTO> roleList = roleService.selectList(roleWrapper);
        
        // 转换为VO对象
        List<RoleVO> roleVOList = roleList.stream().map(role -> {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(role, roleVO);
            return roleVO;
        }).collect(Collectors.toList());
        
        return new Result<>(roleVOList);
    }

    @ApiOperation(value = "用户角色关联列表",notes = "用户角色关联列表")
    @PostMapping("/queryPageList")
    public Result<Page<EmployeeRoleDTO>> queryPageList(EmployeeRoleBO bo){
        Wrapper<EmployeeRoleDTO> wrapper = new EntityWrapper<>();
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<EmployeeRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = userRoleService.selectPage(page, wrapper);

        return new Result<>(page);
    }
}